#import "KFMovieView.h"

#import "KeyFrame.h"

#import "KFActorView.h"
#import "KFMouseState.h"

@implementation KFMovieView
@synthesize selected;
@synthesize mouseState;

-(void) setSelected:(NSView*)theView
{
    if(self.selected != theView)
    {
        [selected autorelease];
        selected = [theView retain];

        for(NSView* view in self.subviews)
        {
            if( [view isKindOfClass:[KFActorView class]])
            {
                ((KFActorView*)view).selected = NO;
            }            
        }
        if( [theView isKindOfClass:[KFActorView class]])
        {
            ((KFActorView*)theView).selected = YES;
        }
    }
}

- (void)drawRect:(NSRect)rect
{
    NSGraphicsContext* theContext = [NSGraphicsContext currentContext];
    [theContext saveGraphicsState];
        
    NSColor *col = [NSColor colorWithCalibratedRed:1.0 green:1.0 blue:1.0 alpha:1.0];
    [col set];
    
    
    NSRectFill(self.bounds);
    
    [theContext restoreGraphicsState];
}


- (BOOL)acceptsFirstResponder {
    return YES;
}

- (void)mouseDown:(NSEvent *)theEvent {
    
    [self.window makeKeyWindow];
    
    NSPoint location = [self convertPoint:[theEvent locationInWindow] fromView:nil]; 
   
    for(NSView* view in self.subviews)
    {
        if( [view hitTest:location] )
        {
            self.selected = view;
            break;
        }
    }
    
    self.mouseState = [KFMouseState mouseState];
    self.mouseState.startLocation = location;
    self.mouseState.lastLocation = location;
    
    //[super mouseDown:theEvent];
    
}


-(void)mouseDragged:(NSEvent *)theEvent
{
    if (self.mouseState != nil)
    {
        NSPoint location=[self convertPoint:[theEvent locationInWindow] fromView:nil];
        
        
        // offset the pill by the change in mouse movement
        // in the event
        NSRect frame = self.selected.frame;
        frame.origin =  KFPointUtil::add( KFPointUtil::sub(location, self.mouseState.lastLocation), frame.origin);   
        self.selected.frame = frame;
        self.mouseState.lastLocation = location;
        
        [self autoscroll:theEvent];
    }
}

-(void)mouseUp:(NSEvent *)event
{
    self.mouseState = nil;
    
    [NSCursor pop];    
    [[self window] invalidateCursorRectsForView:self];
}








@end
